use crate::{ADDRS, GLOBAL_CONFIG};

use super::address::{Address, AddressLabel};
use rusqlite::{Connection, Result};

#[tauri::command]
pub fn query_addr(sth: &str) -> Vec<Address> {
    println!("开始查询");
    let mut match_addr = Vec::new();
    for (_tel, addr) in ADDRS.lock().unwrap().iter() {
        let concat_label = addr.tags.join("").to_ascii_lowercase();
        if addr.name.contains(sth) || addr.tel.contains(sth) || concat_label.contains(&sth.to_ascii_lowercase()) {
            match_addr.push((addr).clone());
        }
    }
    match_addr
}

/**
 * 初始化数据库，如果有数据则加载
 */
pub fn load_all() -> Result<()> {
    let conn = Connection::open(GLOBAL_CONFIG.lock().unwrap().address.db_file.clone())?;
    conn.execute_batch(
        "BEGIN;
        CREATE TABLE IF NOT EXISTS address(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT,
                tel TEXT
                );
            CREATE TABLE IF NOT EXISTS label(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                label TEXT UNIQUE
            );
            CREATE TABLE IF NOT EXISTS addr_label(
                addr_id INTEGER NOT NULL,
                label_id INTEGER NOT NULL
            );
            COMMIT;",
    )?;

    let mut stmt = conn.prepare(
        "
        SELECT a.id, a.name, a.tel, l.label FROM address a 
        LEFT JOIN addr_label al ON a.id = al.addr_id 
        LEFT JOIN label l ON l.id = al.label_id
        ORDER BY a.id DESC
        ",
    )?;

    let address_iter = stmt.query_map([], |row| {
        Ok(AddressLabel {
            id: row.get(0)?,
            name: row.get(1)?,
            tel: row.get(2)?,
            label: row.get(3)?,
        })
    })?;

    for addr_label in address_iter {
        println!("{:?}", addr_label);
        let mut addrs = ADDRS.lock().unwrap();
        if let Some(addr) = addrs.get_mut(&addr_label.as_ref().unwrap().id) {
            addr.tags.push(addr_label.unwrap().label.unwrap());
        } else {
            let addr = Address::new_from_address_label(addr_label.unwrap());
            addrs.insert(addr.id, addr);
        }
    }
    println!("{:?}", ADDRS.lock().unwrap());
    Ok(())

}

#[tauri::command]
pub fn query_by_id(id: i64) -> Address {
    ADDRS.lock().unwrap().get(&id).unwrap().clone()
}
